package com.fzk.blog.satoken;

/**
 * @author fzk
 * @date 2021-07-14 14:29
 */

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpInterface;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fzk.blog.bean.vo.UserInfo;
import com.fzk.blog.settings.service.IUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 */
@Component    // 保证此类被SpringBoot扫描，完成Sa-Token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private IUserService userService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 本list仅做模拟，实际项目中要根据具体业务逻辑来查询权限
        List<String> list = new ArrayList<String>();
        list.add("101");
        list.add("user-add");
        list.add("user-delete");
        list.add("user-update");
        list.add("user-get");
        list.add("article-get");
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> list = new ArrayList<>();
        UserInfo userInfo = null;
        try {
            userInfo = userService.getMyInfo(Integer.parseInt(loginId.toString()));
            String roleName = userInfo.getRoleName();
            if (roleName == null)
                throw new NotLoginException("用户可能已经被删除", "login", NotLoginException.INVALID_TOKEN);
            list.add(roleName);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return list;
    }

}
